import 'package:flutter/material.dart';

class NumberInput extends StatefulWidget {
  final double value;
  final double step;
  final double minValue;
  final double maxValue;
  final bool editable;
  final void Function(double value) onNumber;
  final Axis axis;
  final bool showLabel;

  const NumberInput({Key key, this.value = 0.0, this.step = 1.0, this.minValue = 0.0, this.maxValue = 100.0, @required this.onNumber, this.axis = Axis.horizontal, this.editable = false, this.showLabel = true}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return _NumberInputState();
  }

}

class _NumberInputState extends State<NumberInput> {
  double _tryParse(String textOfNumber){
    var value = 0.0;
    try {
      value = num.parse(_controller.text).toDouble();
    }
    catch (exception){}

    return value;
  }

  TextEditingController _controller;
  double get value => _tryParse(_controller.text);
  set value(double _value) => _controller.text = _value.toString();

  @override
  void initState() {

    _controller = TextEditingController(text: widget.value.toString());
    _controller.addListener((){
      widget.onNumber(_tryParse(_controller.text));
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    var primaryColor = Theme.of(context).primaryColor;
    var widgets = <Widget>[
      IconButton(
        icon: Icon(Icons.add, color: Colors.white,),
        onPressed: (){
          if (value < widget.maxValue)
            setState(() {
              value += widget.step;
            });
        },
      ),
      if (widget.showLabel) Expanded(
        child: Container(
          color: Theme.of(context).scaffoldBackgroundColor,
          margin: EdgeInsets.all(1.0),
          child: TextField(
            controller: _controller,
            textDirection: TextDirection.ltr,
            textAlign: TextAlign.center,
            keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
            decoration: InputDecoration(
                border: InputBorder.none
            ),
            enabled: widget.editable,
            cursorColor: primaryColor,
          ),
        ),
      ),
      IconButton(
        icon: Icon(Icons.remove, color: Colors.white,),
        onPressed: (){
          if (value > widget.minValue)
            setState(() {
              value -= widget.step;
            });
        },
      ),
    ];

    Widget buildingWidget = Container(
      width: double.infinity,
      color: primaryColor,
      child: widget.axis == Axis.horizontal ? Row(children: widgets, mainAxisAlignment: MainAxisAlignment.spaceBetween,) : Column(children: widgets, mainAxisAlignment: MainAxisAlignment.spaceBetween,)
    );

    buildingWidget = ClipRRect(
      child: buildingWidget,
      borderRadius: BorderRadius.circular(15.0),
    );
    return buildingWidget;
  }
}